import Koa from 'koa';
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const mongoose = require('mongoose')
const mongoConfig = require('./db/config')
const users = require('./routes/users')
const todolist = require('./routes/todolist')
import passport from './until/passport'
import session from 'koa-generic-session'
import Redis from 'koa-redis'

// error handler
onerror(app)

// middlewares
app.keys = ['thgg', 'keyskeys'] // 签名字段
app.proxy = true
app.use(session({key: 'thgg', prefix: 'thgg:uid',  store: Redis({})})) // 开启session   在redis中的key
app.use(bodyparser({
  formLimit:"50mb",
  jsonLimit:"50mb",
  textLimit:"50mb",
  enableTypes:['json', 'form', 'text']
}))
app.use(passport.initialize()) // 使用passport
app.use(passport.session()) // passport使用session
mongoose.connect(mongoConfig.dbs, {
  useFindAndModify: false,
  useNewUrlParser: true // 连接mongdb数据库
})


app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(todolist.routes(), todolist.allowedMethods())
app.use(users.routes(), users.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
